package dao

import (
	"gorm.io/gorm"
	"lib/id"
	"lib/structs/cap"
	"lib/structs/tables"
	"lib/utils"
)

var HostDao = new(hostDao)

type hostDao struct{}

func (d hostDao) BindClusterId(hostId, clusterId int64) (err error) {
	err = DB.Model(&tables.CapHost{}).Where("id = ?", hostId).Update("cluster_id", clusterId).Error
	return err
}
func (d hostDao) Page(in cap.SearchHostForm) (li []tables.CapHost, total int64, err error) {
	tx := DB.Model(&tables.CapHost{})
	if in.Ip != "" {
		tx.Where(" ip like ?", "%"+in.Ip+"%")
	}
	if in.GuaProtocol != "" {
		tx.Where(" gua_protocol = ?", in.GuaProtocol)
	}
	tx.Count(&total).Offset((in.PageNum - 1) * in.PageSize).Limit(in.PageSize).Find(&li)
	err = tx.Error
	return
}

func (d hostDao) ClusterList() (li []tables.CapCluster, err error) {
	err = DB.Model(&tables.CapCluster{}).Find(&li).Error
	return
}

func (d hostDao) HostList() (li []tables.CapHost, err error) {
	err = DB.Model(&tables.CapHost{}).Find(&li).Error
	return
}

func (d hostDao) CountHostNumByClusterId(cluId int64) (num int64, err error) {
	err = DB.Raw("select count(*) from cap_host where cluster_id = ?", cluId).Scan(&num).Error
	return
}

func (d hostDao) FindById(hid int64) (m tables.CapHost, err error) {
	err = DB.Model(&tables.CapHost{}).Where("id = ?", hid).Find(&m).Error
	return
}

func (d hostDao) FindByUid(uid string) (m tables.CapHost, err error) {
	err = DB.Model(&tables.CapHost{}).Where("uid = ?", uid).Find(&m).Error
	return
}
func (d hostDao) FindByClusterId(clusterId int64) (li []tables.CapHost, err error) {
	err = DB.Model(&tables.CapHost{}).Where("cluster_id = ?", clusterId).Find(&li).Error
	return
}

func (d hostDao) FindClusterByCluId(cluId int64) (m tables.CapCluster, err error) {
	err = DB.Model(&tables.CapCluster{}).Where("id = ?", cluId).Find(&m).Error
	return
}

func (d hostDao) Create(m tables.CapHost) (err error) {
	err = DB.Model(&tables.CapHost{}).Create(&m).Error
	return
}

func (d hostDao) UpdateById(m tables.CapHost) (err error) {
	err = DB.Model(&tables.CapHost{}).Where("id =?", m.Id).Updates(&m).Error
	return
}

// BatchInsertAppCollectList 批量写入云应用采集信息，写入前会先删除旧的记录
func (d hostDao) BatchInsertAppCollectList(li []tables.CapAppCollect) (err error) {
	ids := make([]int64, 0)
	for _, item := range li {
		item.Id = id.GetSnowId()
		if !utils.Contains(ids, item.HostId) {
			ids = append(ids, item.HostId)
		}
	}
	err = DB.Transaction(func(tx *gorm.DB) error {
		err = tx.Model(&tables.CapAppCollect{}).
			Where("host_id in (?)", ids).Delete(&tables.CapAppCollect{}).Error
		if err != nil {
			return err
		}
		err = tx.Create(&li).Error
		return err
	})
	return err
}
